//
//  MyTextDrawingView.m
//  sandbox
//
//  Created by 杨岑 on 7/7/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "MyTextDrawingView.h"

@implementation MyTextDrawingView
{
    NSMutableArray* _blocks;
    NSMutableArray* _rects;
}

- (instancetype)initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame:frameRect];
    if (self)
    {
        NSFont* font = [NSFont userFontOfSize:16];
        
        _blocks = [NSMutableArray array];
        _rects = [NSMutableArray array];
        
        for (int i = 0; i < 3; i++)
        {
            NSTextBlock* block = [[NSTextBlock alloc] init];
            [block setValue:100 type:NSTextBlockPercentageValueType forDimension:NSTextBlockWidth];
            
            NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
            [paragraphStyle setTextBlocks:@[block]];
            paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
            
            NSDictionary* attrs = @{NSFontAttributeName: font,
                                    NSForegroundColorAttributeName: [NSColor brownColor],
                                    NSParagraphStyleAttributeName: paragraphStyle
                                    };
            
            NSMutableAttributedString* s = [[NSMutableAttributedString alloc] init];
            [s appendAttributedString:[[NSAttributedString alloc] initWithString:@"test string abc\nline2 test test" attributes:attrs]];
            //[s addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [s length])];
            
            [_blocks addObject:s];
        }
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    
    CGFloat y = 0;
    for (NSAttributedString* s in _blocks)
    {
        NSRect rect = [s boundingRectWithSize:NSMakeSize(self.bounds.size.width, FLT_MAX) options:0];
        rect = NSMakeRect(0, y, rect.size.width, rect.size.height);
        [s drawInRect:rect];
        NSFrameRect(rect);
        
        y += rect.size.height;
        y += 10;
    }
}

- (void)resetCursorRects
{
    CGFloat y = 0;
    NSCursor* cursor = [NSCursor openHandCursor];
    
    for (NSAttributedString* s in _blocks)
    {
        NSRect rect = [s boundingRectWithSize:NSMakeSize(self.bounds.size.width, FLT_MAX) options:0];
        [self addCursorRect:NSMakeRect(0, y, rect.size.width, rect.size.height) cursor:cursor];
        y += rect.size.height;
        y += 10;
    }
}

@end
